import axios from 'axios';
import { browserHistory } from 'react-router' ;

var http = axios.create({
  baseURL: 'http://localhost:8080',
  timeout: 1000,
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
  }
});

if ( localStorage.jwtToken ) {
  http.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.jwtToken ; 
}

http.interceptors.request.use(function (config) {
    // Do something before request is sent
    if ( localStorage.jwtToken ) {
      http.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.jwtToken ; 
    }

    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

http.interceptors.response.use(function (response) {
    return response;
  },function(error){
    if ( error.response.status === 401 ){
      browserHistory.push('/backend/login') ;
    }
    return Promise.reject(error);
  });


export default http ;